//
//  JXWebViewController.m
//  JiaoX
//
//  Created by 尹桥印 on 14/11/13.
//  Copyright (c) 2014年 北京娇羞科技有限公司. All rights reserved.
//

#import "JXWebViewController.h"
#import "CartView.h"
#import "RegexKitLite.h"
#import "CartInfoDao.h"
#import "HomeDataTool.h"
#import "ProductDetail.h"
#import "AddProdToCartUtil.h"
#import "JXCartController.h"
#import "AnimUtils.h"

@interface JXWebViewController ()<UIWebViewDelegate>

@property(nonatomic,strong) UIWebView *webview;
@property(nonatomic,copy) NSString *url;//页面访问地址
@property(nonatomic,copy) NSString *title;//页面标题
@property(nonatomic,strong)CartInfoDao *cartDao;
@property(nonatomic,strong)CartView *cartView;
@property(nonatomic,strong)ProductDetail *prodDetail;
@property(nonatomic,strong)UIImageView *animImage;
@end

@implementation JXWebViewController

+(instancetype)initWithUrl:(NSString *)url title:(NSString *)title{
    JXWebViewController *webView = [[self alloc] init];
    webView.url = url;
    webView.title = title;
    return webView;
}

-(void)initRightView{
    _cartView =[[CartView alloc]initWithImage:@"ic_webview_cart"];
    [_cartView addTarget:self action:@selector(toCartCtrl) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:_cartView];
    self.navigationItem.rightBarButtonItem = item;
}

/**
 *  去购物车
 */
-(void)toCartCtrl{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"to_cartctrl" object:nil];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    //重写返回键
    UIView *view = self.navigationItem.leftBarButtonItem.customView;
    if ([view isKindOfClass:[UIButton class]]) {
        [((UIButton *)view) removeTarget:self.navigationController action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        [((UIButton *)view) addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    }
    
    [self initRightView];
    
    _cartDao = [[CartInfoDao alloc]init];
    [_cartView setNum:[_cartDao queryProdsCount]];
    //初始化webview
    _webview = [[UIWebView alloc]init];
    _webview.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    [_webview setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:_webview];
    _webview.delegate = self;
    //加载数据
    [_webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_url]]];
}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSString *url = [request.URL absoluteString];
    JXLog(@"url=%@",url);
    if([url rangeOfString:@"addCartProdId="].location != NSNotFound){
        NSString *regexString  = @"addCartProdId=([0-9]*)";
        NSString *prodId = [url stringByMatching:regexString];
        prodId = [prodId substringFromIndex:[prodId rangeOfString:@"="].location+1];
        [self requestProdDetail:prodId];
        return NO;
    }
    //返回yes会继续去加载网页，返回No不会去继续加载网页
    return [Utils dealUrlWithController:self url:url title:@"" fromWebView:YES];
}

-(void)webViewDidFinishLoad:(UIWebView *)webView{
    NSString *theTitle=[webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    self.title = theTitle;
    
    CGSize actualSize = [webView sizeThatFits:CGSizeZero];
    _webview.scrollView.contentSize = actualSize;
    
    //根据webview加载的情况判断是否添加上返回的手势事件
    if (![self isCanBack]) {
        if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]){
            self.navigationController.interactivePopGestureRecognizer.enabled = NO;
        }
    }else{
        if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]){
            self.navigationController.interactivePopGestureRecognizer.enabled = YES;
        }
    }
}

//----------------以下为加入购物车代码--------------//
-(void)requestProdDetail:(NSString *)prodId{
    MBProgressHUD *HUD = [DialogUtils showLoadingWithView:self.navigationController.view];
    [HomeDataTool getProdDetailWithProdId:prodId success:^(ProductDetail *result) {
        _prodDetail = result;
        [self addToCart:_prodDetail];
        [HUD hide:YES];
    } failure:^(NSError *error) {
        [DialogUtils showTipsWithView:self.navigationController.view String:@"加入购物车失败"];
        [HUD hide:YES];
    }];
}

-(void)addToCart:(ProductDetail *)detail{
    if (TOKEN) {//代表登录过
        //向服务器提交数据
        if ([AddProdToCartUtil assertAddCart:self.navigationController.view productDetail:detail dao:_cartDao addNumber:1 selectSkuPosition:0]) {
            [AddProdToCartUtil postProdToServer:self.navigationController.view productDetail:detail selectSkuPosition:0 prodCount:1 ctrl:self];
        }
    }else{
        if ([AddProdToCartUtil assertAddCart:self.navigationController.view productDetail:detail dao:_cartDao addNumber:1 selectSkuPosition:0]) {// 判断活动的商品
            //直接开始动画
            [self startShopCartAnim];
        }
    }
}


-(void)viewWillAppear:(BOOL)animated{
    JXLog(@"viewWillAppear");
    NSString *url = [self.webview.request.URL absoluteString];
    if ([url rangeOfString:@"needLogin"].location !=NSNotFound && [url rangeOfString:@"token"].location ==NSNotFound) {
        if (TOKEN) {
            NSString *loadUrl = [NSString stringWithFormat:@"%@&token=%@",url,TOKEN];
            [self.webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:loadUrl]]];
        }
    }
}

-(void)commitSuccess{
    //这个地方需要执行动画
    [self startShopCartAnim];
}

-(void)commitFailure{
    [DialogUtils showTipsWithView:self.navigationController.view String:@"加入购物车失败"];
}

-(void)startShopCartAnim{
    //添加到数据库
    [AddProdToCartUtil addProdToDb:_prodDetail.prodSub[0] prodDetail:_prodDetail dao:_cartDao prodCount:1];
    
    //执行加入购物车动画.动画执行完毕更新购物车数量图标
    UIImage *image = [UIImage imageNamed:@"ic_webview_add_cart"];
    _animImage = [[UIImageView alloc]initWithImage:image];
    _animImage.size = CGSizeMake(JXScreenW/2, JXScreenW/2);
    [_animImage.layer setCornerRadius:JXScreenW/4];
    _animImage.layer.masksToBounds = YES;
    _animImage.center = _webview.center;
    [self.view addSubview:_animImage];
    [AnimUtils addToCartAnim:_animImage startView:_webview endView:_cartView delegate:self adverse:-1];
}

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    [_animImage removeFromSuperview];
    //更新购物车图标
    [self updateCartViewNum];
}

/**
 *  更新购物车数量
 */
-(void)updateCartViewNum{
    NSInteger count = [_cartDao queryProdsCount];
    [_cartView setNum:count];
}

//----------------以上为加入购物车代码--------------//

-(void)dealloc{
    self.webview.delegate = nil;
    [self.webview stopLoading];
}

-(void)back{
    if ([self isCanBack]) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [_webview goBack];
    }
}

-(BOOL)isCanBack{
    return ![_webview canGoBack];
}

@end
